var datatable2='';
var todayDate = moment().startOf('day');
var YM = todayDate.format('YYYY-MM');
// 加载表格
var DatatableRemoteAjaxDemo = function() {
	// == Private functions
	var demo = function loadTableData() {
		$('#m_datatable_pzgl').mDatatable('destroy');
		datatable = $('#m_datatable_pzgl').mDatatable(
			{
				data : {
					type : 'remote',
					source : {
						read : {
							method : 'POST',
							url : '/yyglLocationManagement/getLocation'
						}
					},
					pageSize : 10,
					serverPaging : true,
					serverFiltering : false,
					serverSorting : false
				},
				autoWidth:false,
				// layout definition
				layout : {
					scroll : true,
					footer : false,
					height: 535
				},
				sortable : false,
				pagination : true,
				search : false,
				toolbar : {
					items : {
						pagination : {
							pageSizeSelect: [10, 15, 20]
						}
					}
				},
				// columns definition
				columns : [
						{
					  	field: "resId",
                        title: "#",
                        width: 40,
                        sortable: false,
                        textAlign: 'center',
                        selector: {class: 'm-checkbox--solid m-checkbox--brand'}
						},
						{
							field : 'userType',
							title : '用户类型',
							width : 80,
						},
						{
							field : 'userName',
							title : '用户名',
							width : 120
						},
						{
							field : 'userMac',
							title : '用户MAC地址',
							width : 90
						},
						{
							field : 'userAddress',
							title : '用户地址',
							width : 60
						},
						{
							field : 'innerPhone',
							title : '内网电话',
							width : 80
						},
						{
							field : 'userTelphone',
							title : '手机号码',
							width : 60
						},
						{
							field : 'remark',
							title : '备注',
							width : 60
						}
					]
			});

		var query = datatable.getDataSourceQuery();
		datatable2 = datatable;
		$('#search').click(function() {
			datatable.reload();
			datatable.search2([ $('#find_username').val(),$('#find_usermac').val(),$('#find_useradress').val(),$('#find_innerphone').val(),$('#find_usertype').val()], ['userName','userMac','userAddress','innerPhone','userType']);
		});
	};

	return {
		init : function() {
			demo();
		}
	};
}();
 



// 重置按钮
$('#reset').click(function() {
	$('#almName').val("");
	$('#almcls').val("");
	$('#systemType').val("");
	$('#signalType').val("");
	$('#entityTypeId').val("");
	//$("#signalType").html("");
	$("select[name='signalType']").find("option").remove();
	$("select[name='signalType']").append(new Option("请选择",""));
	//$('#devName').val("");
});


//下拉加载用户类型选择
$(function() {
	$("select[name='usertype']").find("option").remove();
	$("select[name='usertype']").append(new Option("请选择",""));
	$("select[name='find_usertype']").find("option").remove();
	$("select[name='find_usertype']").append(new Option("请选择",""));

	$("#usertype").append("<option value="+"0"+">运维人员</option>");
	$("#usertype").append("<option value="+"1"+">其他</option>");

	$("#find_usertype").append("<option value="+"0"+">运维人员</option>");
	$("#find_usertype").append("<option value="+"1"+">其他</option>");

    $("#update_usertype").append("<option value="+"0"+">运维人员</option>");
    $("#update_usertype").append("<option value="+"1"+">其他</option>");
});



/*$(function() {
	$("select[name='add_SignalType']").append(new Option("请选择",""));
	$("#system").change(function() {
		$("select[name='add_SignalType']").find("option").remove();
		$("select[name='add_SignalType']").append(new Option("请选择",""));
		var system = ($(this).val());
		$.ajax({
			type : "post",
			url : "/yyglAlarmConfiguration/getSignalTypeBySystem",
			dataType : 'json',
			async: false,	
			data : {"system":system},
			success : function(data) {
				for (var i = 0; i < data.length; i++) {
					var name = data[i].name;
					var resId = data[i].code;
					var opt = new Option(name,resId);
					$("select[name='add_SignalType']").append(opt);
				}
			}
		});
		
	});
});*/

/*
$(function() {
	$("select[name='signalType']").append(new Option("请选择",""));
	$("#systemType").change(function() {
		$("select[name='signalType']").find("option").remove();
		$("select[name='signalType']").append(new Option("请选择",""));
		var system = ($(this).val());
		$.ajax({
			type : "post",
			url : "/yyglAlarmConfiguration/getSignalTypeBySystem",
			dataType : 'json',
			async: false,
			data : {"system":system},
			success : function(data) {
				for (var i = 0; i < data.length; i++) {
					var name = data[i].name;
					var resId = data[i].code;
					var opt = new Option(name,resId);
					$("select[name='signalType']").append(opt);
				}
			}
		});

	});
});
*/

// 下拉框加载告警级别

/*$(function() {
	$("#add_almcls").html("");
	$("#update_almcls").html("");
	$.ajax({
		type : "get",
		url : "/yyglAlarmConfiguration/getalmcls",
		dataType : 'json',
		async: false,
		data : {},
		success : function(data) {
			$("#add_almcls").append("<option value=''>请选择</option>");
			for (var i = 0; i < data.length; i++) {
				$("#add_almcls").append("<option value="+data[i].code+">"+data[i].name+"</option>");
			}
			$("#update_almcls").append("<option value=''>请选择</option>");
			for (var i = 0; i < data.length; i++) {
				$("#update_almcls").append("<option value="+data[i].code+">"+data[i].name+"</option>");
			}
		}
	});
});*/


// 下拉框加载运算符

/*$(function() {
	$("#judcls").html("");
	$("#update_judcls").html("");
	$.ajax({
		type : "get",
		url : "/yyglAlarmConfiguration/getoperation",
		dataType : 'json',
		async: false,
		data : {},
		success : function(data) {
			$("#judcls").append("<option value=''>请选择</option>");
			for (var i = 0; i < data.length; i++) {
				$("#judcls").append("<option value="+data[i].code+">"+data[i].name+"</option>");
			}
			$("#update_judcls").append("<option value=''>请选择</option>");
			for (var i = 0; i < data.length; i++) {
				$("#update_judcls").append("<option value="+data[i].code+">"+data[i].name+"</option>");
			}
		}
	});
});*/

// 下拉框加载上发状态
/*$(function() {
	$("#send_status").html("");
	$("#update_send_status").html("");
	$.ajax({
		type : "get",
		url : "/yyglAlarmConfiguration/getsendStatus",
		dataType : 'json',
		async: false,
		data : {},
		success : function(data) {
			$("#send_status").append("<option value=''>请选择</option>");
			for (var i = 0; i < data.length; i++) {
				$("#send_status").append("<option value="+data[i].code+">"+data[i].name+"</option>");
			}
			$("#update_send_status").append("<option value=''>请选择</option>");
			for (var i = 0; i < data.length; i++) {
				$("#update_send_status").append("<option value="+data[i].code+">"+data[i].name+"</option>");
			}
		}
	});
});*/

// 下拉框加载告警类型
/*$(function() {
	$("#entity_type_id").html("");
	$("#entityTypeId").html("");
	$("#update_entity_type_id").html("");
	$.ajax({
		type : "get",
		url : "/yyglAlarmConfiguration/getentityTypeId",
		dataType : 'json',
		async: false,
		data : {},
		success : function(data) {
			$("#entity_type_id").append("<option value=''>请选择</option>");
			$("#entityTypeId").append("<option value=''>请选择</option>");
			for (var i = 0; i < data.length; i++) {
				$("#entity_type_id").append("<option value="+data[i].code+">"+data[i].name+"</option>");
				$("#entityTypeId").append("<option value="+data[i].code+">"+data[i].name+"</option>");
			}
			$("#update_entity_type_id").append("<option value=''>请选择</option>");
			for (var i = 0; i < data.length; i++) {
				$("#update_entity_type_id").append("<option value="+data[i].code+">"+data[i].name+"</option>");
			}
		}
	});
});*/

// 添加-提交按钮
$("#submit").on("click",function(){
	var userName = $("#user_Name").val();
	var userMac = $("#user_mac").val();
	var userType = $("#usertype").find("option:selected").val();


//	alert(userType);

	var userAddress = $('#user_address').val();
	var innerPhone = $('#inner_phone').val();
	var userTelphone = $('#user_telphone').val();
	var remark = $('#remark').val();

/*定位管理 必填项 管理*/
	if(
		 '' == userName || undefined=== userName || null === userName ||
		 '' == userMac || undefined=== userMac || null === userMac ||
		 '' == userType || undefined=== userType || null === userType ||
		 '' == userAddress || undefined=== userAddress || null === userAddress ||
		 '' == innerPhone || undefined=== innerPhone || null === innerPhone ||
		 '' == userTelphone || undefined=== userTelphone || null === userTelphone){
		swal("警告!", "请将带*处填齐,不可为空!", "warning");
		return;
	}else {
		//可发送，提交过程中按钮加载中效果
		//$("#submit").addClass("m-loader m-loader--light m-loader--right").attr("disabled","disabled").text("提交中");

		var ajaxPromise = new Promise(function(resolve){
			resolve();
		});

		ajaxPromise.then(function(){
			return $.ajax({
				url: '/yyglLocationManagement/beforeAddQuery',
				type: 'post',
				async: false,
				dataType: 'json',
				data: {
					'userName': userName,
					'userMac': userMac,
					'userType': userType,
					'userAddress': userAddress,
					'innerPhone' : innerPhone,
					'userTelphone' : userTelphone,
					'remark' : remark
				},
				success: function (data) {
					//$("#submit").addClass("m-loader m-loader--light m-loader--right").attr("disabled","disabled").text("提交中");
					swal({
						title: "请稍等",
						text:"正在添加数据，请稍候...",
						type: "warning",
						showConfirmButton:false,
						allowOutsideClick: false //弹框外是否可点
					});
					return data;
				}
			});
		}).then(function(data){
			if(data.result == "SUCCESS"){
				alert("success");
				setTimeout(function() {
					$.ajax	({
						url: '/yyglLocationManagement/insert',
						type: 'post',
						async: false,
						dataType: 'json',
						data: {
							'userName': userName,
							'userMac': userMac,
							'userType': userType,
							'userAddress': userAddress,
							'innerPhone' : innerPhone,
							'userTelphone' : userTelphone,
							'remark' : remark
						},
						success: function (data) {
							if(data.result == "SUCCESS_FLAG"){
							datatable2.reload();// 重新加载表格
							swal({
							      title: "新建成功",
							      type: "success",
							      showConfirmButton: false,
							      timer: 2000
							     });
							//swal("提示", "添加成功", "success");// 弹出成功提示框
							$("#add_modal").modal("toggle");// modal插件，状态反转，关闭则显示，显示则关闭
							//提交完成后按钮取消加载中效果
							//$("#submit").removeClass("m-loader m-loader--light m-loader--right").removeAttr("disabled").text("提交");

								 $("#user_Name").val("");
								 $("#user_mac").val("");
								 $('#user_address').val("");
								 $('#inner_phone').val("");
								 $('#user_telphone').val("");
								 $('#remark').val("");
					}
						},
						error: function () {
							//提交完成后按钮取消加载中效果
							//$("#submit").removeClass("m-loader m-loader--light m-loader--right").removeAttr("disabled").text("提交");
							swal("提示", "未知原因添加失败", "error");
						},
						clearForm: false,// 禁止清除表单
						resetForm: false // 禁止重置表单
					});
				}, 1000);
			}else if(data.result == "ERROR"){
				//提交完成后按钮取消加载中效果
				//$("#submit").removeClass("m-loader m-loader--light m-loader--right").removeAttr("disabled").text("提交");
				swal("提示", "规则重复或无效，请重新录入!", "error");
			}

		})

	}
});

$('#reset2').click(function() {
	$("#pipe").val("");
	$("#cabin").val("");
	$("#zone").val("");
	$("#system").val("");
	$("select[name='device']").find("option").remove();
	$("select[name='device']").append(new Option("请选择",""));
	$("#add_SignalType").val("");
	$('#judcls').val("");
	$('#judval').val("");
	$('#add_almcls').val("");
	$('#add_almName').val("");
	$('#almstr').val("");
	$('#send_status').val("");
	$('#entity_type_id').val("");
	
	$("select[name='add_SignalType']").find("option").remove();
	$("select[name='add_SignalType']").append(new Option("请选择",""));

});
$('#close_modal').click(function() {
	$("#pipe").val("");
	$("#cabin").val("");
	$("#zone").val("");
	$("#system").val("");
	$("select[name='device']").find("option").remove();
	$("select[name='device']").append(new Option("请选择",""));
	$("#add_SignalType").val("");
	$('#judcls').val("");
	$('#judval').val("");
	$('#add_almcls').val("");
	$('#add_almName').val("");
	$('#almstr').val("");
	$('#send_status').val("");
	$('#entity_type_id').val("");
	
	$("select[name='add_SignalType']").find("option").remove();
	$("select[name='add_SignalType']").append(new Option("请选择",""));

});

// 定位管理 修改 前的数据回显
$('#updateAction').click(function() {
	 var ids = datatable2.rows('.m-datatable__row--active').nodes().find('.m-checkbox--single > [type="checkbox"]').
     
     map(function(i, chk) {
         return $(chk).val();
     });
	 
     if(ids.length == 0){
    	 $('#update_modal').modal('hide');
         swal("操作错误!", "请选择一条需要修改的记录!", "warning");
     }else if(ids.length > 1){
    	 $('#update_modal').modal('hide');
         swal("操作错误!", "只能选择一条需要修改的记录!", "warning");
     }else{
    	var id = ids[0];
    	 $.ajax({
    			url:"/yyglLocationManagement/beforeUpdateQuery",
    			async:false,
    			data:{resId:id},
    			type:"POST",
    			success : function(data) {
    				document.getElementById('update_id').value =data[0].resId;

    				document.getElementById('update_usertype').value =data[0].userType;

    	    		document.getElementById('update_user_Name').value = data[0].userName;
    	    		document.getElementById('update_user_mac').value = data[0].userMac;
    	    		document.getElementById('update_user_address').value = data[0].userAddress;
    	    		document.getElementById('update_inner_phone').value = data[0].innerPhone;
    	    		document.getElementById('update_user_telphone').value = data[0].userTelphone;
    	    		document.getElementById('update_remark').value = data[0].remark;

    			},
    			error : function() {
    				swal("提示", "未知原因获取数据失败！", "error");
    			}
    		});
    	 	$('#update_id').html("");
    		$('#update_modal').modal('show');
     }
});



// 定位管理 修改-提交按钮    对应 locationManagement.html

$('#update_submit').click(function() {

	 var resId = $("#update_id").val();

	var userName = $("#update_user_Name").val();
	var userMac = $("#update_user_mac").val();
	var userType = $("#update_usertype").find("option:selected").val();

	var userAddress = $('#update_user_address').val();
	var innerPhone = $('#update_inner_phone').val();
	var userTelphone = $('#update_user_telphone').val();
	var remark = $('#update_remark').val();

	/*定位管理 必填项 管理*/
	if(
		'' == userName || undefined=== userName || null === userName ||
		'' == userMac || undefined=== userMac || null === userMac ||
		'' == userType || undefined=== userType || null === userType ||
		'' == userAddress || undefined=== userAddress || null === userAddress ||
		'' == innerPhone || undefined=== innerPhone || null === innerPhone ||
		'' == userTelphone || undefined=== userTelphone || null === userTelphone){
		swal("警告!", "请将带*处填齐,不可为空!", "warning");
		return;
	}else{
		var ajaxPromise = new Promise(function(resolve){
			resolve();
		});
		ajaxPromise.then(function(){
			return $.ajax({
				url: '/yyglLocationManagement/beforeUpdateQuery2',      //这一步没有作用直接返回success
				type: 'post',
				async: false,  //同步
				dataType: 'json',
				data: {
					'resId': resId,          //修改需要传递userId  主键自动生成
					'userName': userName,
					'userMac': userMac,
					'userType': userType,
					'userAddress': userAddress,
					'innerPhone' : innerPhone,
					'userTelphone' : userTelphone,
					'remark' : remark
				},
				success: function (data) {
					//$("#submit").addClass("m-loader m-loader--light m-loader--right").attr("disabled","disabled").text("提交中");
					swal({
						title: "请稍等",
						text:"正在修改数据，请稍候...",
						type: "warning",
						showConfirmButton:false,
						allowOutsideClick:false //弹框外是否可点
					});
					return data;
				}
			});
		}).then(function(data){
			if(data.result == "SUCCESS"){
				setTimeout(function(){

					var obj = JSON.stringify({
						'resId': resId,
						'userName': userName,
						'userMac': userMac,
						'userType': userType,
						'userAddress': userAddress,
						'innerPhone' : innerPhone,
						'userTelphone' : userTelphone,
						'remark' : remark
					});

					$.ajax({
						url: '/yyglLocationManagement/update',     //修改
						type: 'post',
						async : false,
						dataType: 'json',
						data : obj,
						contentType: 'application/json;charset=utf-8',
						success : function(data) {
							if (data.result == "SUCCESS_FLAG") {
								swal({
									title: "修改成功",
									type: "success",
									showConfirmButton: false,
									timer: 2000
								});
								$("#update_modal").modal("toggle");// modal插件，状态反转，关闭则显示，显示则关闭

								$("#update_id").val("");
								$("#update_user_Name").val("");
								$("#update_user_mac").val("");
								$('#update_user_address').val("");
								$('#update_inner_phone').val("");
								$('#update_user_telphone').val("");
								$('#update_remark').val("");

								datatable2.reload();// 重新加载表格
							} else{
								swal("提示", "修改失败", "error");
							}
						},
						error : function() {
							swal("提示", "未知原因修改失败", "error");
						}
					})
				},1000);
			}else if(data.result == "ERROR"){
				swal("提示", "重复或无效，请重新录入!", "error");
			}
		})
	}
});

// 删除
$('#deleteAction').click(function() {

	var ids = datatable2.rows('.m-datatable__row--active').nodes().find('.m-checkbox--single > [type="checkbox"]').
    map(function(i, chk) {
        return $(chk).val();
    });
    if(ids.length == 0){
        swal("操作错误!", "请选择一条需要删除的记录!", "warning");

    }else if(ids.length > 1){
   	 $('#update_modal').modal('hide');
     swal("操作错误!", "只能选择一条需要删除的记录!", "warning");
    }else if(ids.length = 1){
    	var resIds =[];
    	for (var i = 0;i< ids.length;i++){
			 resIds[i] = ids[i];
        }
    	swal({
            title: '提示',
            text: "确认删除吗？",
            type: 'warning',
            showCancelButton: true,
            confirmButtonText: '确认',
            cancelButtonText: '取消',
			showLoaderOnConfirm: true, //加载按钮是否可见
			preConfirm: function() {
				var sureBtn = swal.getConfirmButton();
				$(sureBtn).text("删除中");
				return new Promise(function(resolve) {
					setTimeout(function() {
						resolve();
					}, 3000);
				});
			},
			allowOutsideClick: false //弹框外是否可点
        }).then(function(result){
            if (result.value) {
            	$.ajax({
            		url:"/yyglLocationManagement/DeleteWithDelflag",
            		async:false,
            		contentType: 'application/json;charset=UTF-8',
            		data:JSON.stringify(resIds),
            		type:"POST",
            		success : function(data) {
        				if (data.result == "SUCCESS_FLAG") {
        					//swal("提示", "删除成功", "success");// 弹出成功提示框
        					swal({
        						title: "提示",
        						text:"删除成功！",
        						type: "success",
        						//showConfirmButton:false,
        						allowOutsideClick: false //弹框外是否可点
        					});
        					datatable2.reload();// 重新加载表格
        				} else{
        					swal("提示", "删除失败", "error");
        				}
        			},
        			error : function() {
        				swal("提示", "未知原因删除失败", "error");
        			}
            	});
            } 
        });
    }
});



// 通用方法-去除输入框的前后空格
function inputTrimFunc(){
	$('input[type=text]').on("change",function () {
		$('input[type=text]').each(function () {
			this.value=$.trim(this.value);
		})
	});

	$('textarea').on("change",function () {
		$('textarea').each(function () {
			this.value=$.trim(this.value);
		})
	});
}

// 界面加载时
jQuery(document).ready(function() {
	/*debugger;
	alert("1111")*/
	DatatableRemoteAjaxDemo.init();
	inputTrimFunc();
});

//运算符改变时清空判定值
function clearJudval(){
	$('#judval').val("");
    $('#update_judval').val("");
}

/**
 * 导出查询记录
 * @returns
 */
function exportPartialAction(handleType){
	var systemType = $('#systemType').val();
	var signalType = $('#signalType').val();
	var almName = $('#almName').val();
	var almcls = $('#almcls').val();
	var entityTypeId = $('#entityTypeId').val();
	var elemIF = document.createElement("iframe");
	//elemIF.src = "/yyglEquipmentManagement/storageQueryInstanceDownLoad?flag=false&matername="+encodeURI(encodeURI(this.select.matername))+"&matercode="+this.select.matercode+"&supplier="+this.select.supplier+"&whsname="+this.select.whsname;
	elemIF.src = "/yyglAlarmConfiguration/rulesDataDownload?flag=false&" +
		"systemType="+systemType+
		"&signalType="+signalType+
		"&almName="+almName+
		"&almcls="+almcls+
		"&entityTypeId="+entityTypeId;
	elemIF.style.display = "none";
	document.body.appendChild(elemIF);
	if (elemIF.readyState=="complete") {
		// loading('hide');
	}else {
		//  loading('hide');
	}
};

/**
 * 导出所有记录
 * @returns
 */
function exportAllAction(){
	var elemIF = document.createElement("iframe");
	//elemIF.src = "/yyglEquipmentManagement/storageQueryInstanceDownLoad?flag=true";
	elemIF.src = "/yyglAlarmConfiguration/rulesDataDownload?flag=true";
	elemIF.style.display = "none";
	document.body.appendChild(elemIF);
	if (elemIF.readyState=="complete") {
		// loading('hide');
	}else {
		//  loading('hide');
	}
};